<template>
  <div class="main-container">
    <!-- 面包屑 -->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>工艺路线管理</el-breadcrumb-item>
        <el-breadcrumb-item>产品工艺路线</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 新建/修改工艺版本 -->
    <div class="add-procee-pane">
      <!-- 版本/产品信息 -->
      <el-row class="text-center">
        <el-col :span="6">
          <h3>图号：{{ pageProduct.drawingNumber }}</h3>
        </el-col>
        <el-col :span="6">
          <h3>品名：{{ pageProduct.productName }}</h3>
        </el-col>
        <el-col :span="6">
          <h3>材质：{{ pageProduct.materialQuality }}</h3>
        </el-col>
        <el-col :span="6">
          <h3>
            <el-button size="small" type="primary" @click="dialogShow">新建工艺路线</el-button>
            <el-button size="small" @click="goBack">返回</el-button>
          </h3>
        </el-col>
      </el-row>

      <!-- 工艺路线表格 -->
      <!-- 新建工艺版本 按钮 & 弹框 -->

      <el-dialog width="400px" title="新建工艺路线" @close="dialogClose" :visible="dialogVisible">
        <el-form :model="createRouteParam" :rules="rules" ref="form" label-width="100px">
          <el-form-item label="版本号" prop="versionName">
            <el-input v-model="createRouteParam.versionName" placeholder="请输入版本号" class="w200"></el-input>
          </el-form-item>
          <el-form-item label="产品图号" prop="drawingNumber">
            <el-input v-model="createRouteParam.drawingNumber" placeholder="请输入产品图号" class="w200"></el-input>
          </el-form-item>
        </el-form>
        <div style="border-top: 1px solid #eee; padding: 10px 0px; background: #fefefe; text-align: center">
          <el-button type="primary" @click="createNewRoute">下一步</el-button>
          <el-button @click="dialogClose">取消</el-button>
        </div>
      </el-dialog>
      <!-- 工艺路线应用到其他产品 弹框 TODO 考虑复用 -->
      <el-dialog width="400px" title="工艺路线应用" @close="copyRouteDialogClose" :visible="copyRouteVisible">
        <el-form :model="copyRouteForm" :rules="copyRouteRules" label-width="100px">
          <el-form-item label="版本号" prop="versionName">
            <el-input v-model="copyRouteForm.versionName" placeholder="请输入版本号" class="w200"></el-input>
          </el-form-item>
          <el-form-item label="产品图号" prop="drawingNumber">
            <el-input v-model="copyRouteForm.drawingNumber" placeholder="请输入产品图号" class="w200"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="copyRouteForm.remark" placeholder="请输入备注" class="w200"></el-input>
          </el-form-item>
        </el-form>
        <div style="border-top: 1px solid #eee; padding: 10px 0px; background: #fefefe; text-align: center">
          <el-button type="primary" @click="copyRouteToAnother">确定</el-button>
          <el-button @click="copyRouteDialogClose">取消</el-button>
        </div>
      </el-dialog>

      <el-form>
        <div class="border-x mr10">
          <!-- 工艺路线编辑视图 -->
          <div v-if="isEditing">
            <span>&nbsp;&nbsp;版本：{{ editingRoute.versionName }}&nbsp;&nbsp;</span>
            <el-button @click="addFinishProcess()" type="text" icon="el-icon-plus" size="small">整备与完工</el-button>
            <el-button @click="addOutsourceProcess()" type="text" icon="el-icon-plus" size="small">外协成品</el-button>
            <el-button @click="addPurchaseProcess()" type="text" icon="el-icon-plus" size="small">采购成品</el-button>
            <el-table class="mt0 route-table" border stripe :data="editingRoute.processList">
              <!-- Col 1 序号 -->
              <el-table-column prop="sequenceNumber" label="序号" align="center" width="80"></el-table-column>
              <!-- Col 2 工序名称 -->
              <el-table-column prop="processName" label="工序名称" align="center" min-width="100">
                <template slot-scope="scope">
                  <el-autocomplete v-model="scope.row.processName" :fetch-suggestions="querySearch"
                    placeholder="请输入内容"></el-autocomplete>
                </template>
              </el-table-column>
              <!-- Col 3 部门 -->
              <el-table-column prop="department" label="部门" align="center" min-width="100">
                <template slot-scope="scope">
                  <el-select v-if="scope.row.processName != '完工'" v-model="scope.row.department" filterable>
                    <template v-for="option in departmentOptions">
                      <el-option :key="option" :label="option" :value="option"></el-option>
                    </template>
                  </el-select>
                </template>
              </el-table-column>
              <!-- Col 4 单双机 -->
              <el-table-column prop="single" label="单双机" align="center" min-width="100">
                <template slot-scope="scope" v-if="scope.row.department == '加工'">
                  <el-switch style="display: block" v-model="scope.row.single" active-color="#13ce66"
                    inactive-color="#ff4949" active-text="单" inactive-text="双"> </el-switch>
                </template>
              </el-table-column>
              <!-- Col 5 调试工时 -->
              <el-table-column prop="debugHour" label="调试工时" align="center" min-width="100">
                <template slot-scope="scope" v-if="scope.row.department == '加工'">
                  <el-input v-model="scope.row.debugHour" placeholder="调试工时"></el-input>
                </template>
              </el-table-column>
              <!-- Col 6 定额工时 -->
              <el-table-column prop="quotaHour" label="定额工时" align="center" min-width="100">
                <template slot-scope="scope" v-if="scope.row.department == '加工'">
                  <el-input v-model="scope.row.quotaHour" placeholder="定额工时"></el-input>
                </template>
              </el-table-column>
              <!-- Col 7 操作 -->
              <el-table-column label="操作" align="center" fixed="right" min-width="200">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini"
                    @click="insertProcess(scope.row.sequenceNumber, true)">+上</el-button>
                  <el-button type="primary" size="mini"
                    @click="insertProcess(scope.row.sequenceNumber, false)">+下</el-button>
                  <el-button type="danger" size="mini" @click="removeProcess(scope.row.sequenceNumber)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button class="mt5" size="small" type="primary" @click="save">保存</el-button>
            <el-button class="mt5" size="small" type="primary" @click="copy">保存为新版本</el-button>
            <el-button class="mt5" size="small" @click="cancel">取消</el-button>
          </div>
          <!-- 工艺路线显示视图 -->
          <div v-if="!isEditing">
            <div v-if="versionList.length > 0">
              <el-collapse accordion>
                <template v-for="(item, index) in versionList">
                  <el-collapse-item :name="index" :key="index" class="p10-x">
                    <template slot="title">
                      <div class="justify-space-between flex w-100percent">
                        <span>
                          <el-tag type="success">{{ item.versionState }}</el-tag>
                          &nbsp;&nbsp;版本: {{ item.versionName }}
                        </span>
                      </div>
                      <el-button type="primary" size="mini" @click="putIntoProduction(item)"
                        v-if="$checkAuth('工艺路线投产提交') && item.versionState == null">投产</el-button>
                      <el-button type="primary" size="mini" @click="modifyRoute(item)"
                        v-if="$checkAuth('修改工艺路线')">修改</el-button>
                      <el-button type="danger" size="mini" @click="deleteRoute(item)"
                        v-if="$checkAuth('删除工艺路线')">删除</el-button>
                      <el-button type="warning" size="mini" @click="copyRouteDialogOpen(item)"
                        v-if="$checkAuth('新建工艺路线')">应用到其他产品</el-button>
                    </template>
                    <el-table :data="item.processList" stripe border>
                      <el-table-column prop="sequenceNumber" label="序号" min-width="80" align="center">
                      </el-table-column>
                      <el-table-column prop="processName" label="工序" min-width="80" align="center"> </el-table-column>
                      <el-table-column prop="single" label="单机" min-width="80" align="center">
                        <template slot-scope="scope">
                          <div v-if="scope.row.department == '加工'">{{ scope.row.single ? '单机' : '双机' }}</div>
                        </template>
                      </el-table-column>
                      <el-table-column prop="department" label="部门" align="center" min-width="80"></el-table-column>
                      <el-table-column prop="debugHour" label="调试工时" align="center" min-width="80"></el-table-column>
                      <el-table-column prop="quotaHour" label="定额工时" align="center" min-width="80"></el-table-column>
                    </el-table>
                    <el-input type="textarea" style="margin: 10px 0" autosize v-model="item.remark" readonly></el-input>
                  </el-collapse-item>
                </template>
              </el-collapse>
            </div>
            <div v-else>
              <no-data placeholder="这里还没有数据哦，快去新建工艺路线吧~"></no-data>
            </div>
          </div>
        </div>
      </el-form>
      <br /><br />
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import { namespace } from 'vuex-class'
import AddProduct from '../process/addProduct.vue'
import _ from 'lodash'
import { getProcessDetail, creatVersion, designProcess, canModifyProcessRoute } from '@/api/process'
import { Message } from 'element-ui'

const vuexProcess = namespace('TwoProcess')

@Component({
  components: {
    AddProduct
  }
})
export default class EditProcessDetail extends Vue {
  // 工艺路线编辑视图控制
  isEditing: boolean = false
  // 选中的产品
  pageProduct: any = {}
  // 工艺列表
  versionList: any = []

  // 新建工艺路线弹框
  dialogVisible: boolean = false
  createRouteParam: any = {
    drawingNumber: '',
    versionName: ''
  }

  // 受编辑的工艺路线
  editingRoute: any = {}
  processList: any = []
  departmentOptions: any[] = ['采购', '加工', '外协']
  rules: any = {
    versionName: [{ required: true, message: '请填写版本号', trigger: 'blur' }],
    drawingNumber: [{ required: true, message: '请填写产品图号', trigger: 'blur' }]
  }
  copyRouteRules: any = {
    versionName: [{ required: true, message: '请填写版本名称', trigger: 'blur' }],
    drawingNumber: [{ required: true, message: '请填写图号', trigger: 'blur' }]
  }

  @vuexProcess.Action PREDATA_VERSION: any
  @vuexProcess.Action updata_VERSION: any
  @vuexProcess.State processNameList: any

  /**
   * 生命周期函数
   */
  created() {
    this.pageProduct = this.$route.params.product
    let intype = this.$route.params.intype
    console.log('this.pageProduct')
    console.log(this.pageProduct)
    this.PREDATA_VERSION()
    this.getProcessRouteList()
  }
  async getProcessRouteList() {
    let res = await getProcessDetail({ producingId: this.pageProduct.producingId })
    if (res) {
      this.versionList = res.data
    }
  }

  /**
   * 工艺路线投产
   */
  putIntoProduction(route) {
    this.putIntoProducing(route)
  }
  async putIntoProducing(route) {
    let versionIdList: any = []
    versionIdList.push(route.versionId)
    let param = {
      producingId: this.pageProduct.producingId,
      versionIdList: versionIdList
    }
    let res = await designProcess(param)
    if (res) {
      this.getProcessRouteList()
    }
  }

  dialogShow() {
    this.createRouteParam.drawingNumber = this.pageProduct.drawingNumber
    this.dialogVisible = true
  }
  dialogClose() {
    this.dialogVisible = false
  }
  goBack() {
    this.$router.push({
      name: 'menuA1ProductDesign',
      params: {
        from: 'back',
        noticeId: this.pageProduct.noticeId
      }
    })
  }

  copyRouteVisible: boolean = false
  copyRouteForm: any = {
    drawingNumber: '',
    versionName: '',
    remark: ''
  }
  /**
   * 应用到其他产品
   */
  copyRouteDialogOpen(route) {
    this.editingRoute = route
    this.copyRouteVisible = true
  }
  copyRouteDialogClose() {
    this.copyRouteVisible = false
  }
  copyRouteToAnother() {
    this.copyToNewVersion(this.copyRouteForm)
  }

  /**
   * 编辑工艺路线 - 保存为新版本
   */
  copy() {
    if (this.validateSubmitProcessList()) {
      this.$prompt('请输入新的版本号', '新建工艺路线：图号' + this.pageProduct.drawingNumber, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((value: any) => {
        if (String(value.value) == 'null') {
          this.$alert('版本号不能为空')
        } else {
          this.createRouteParam.drawingNumber = this.pageProduct.drawingNumber
          this.createRouteParam.versionName = String(value.value)
          this.copyToNewVersion(this.createRouteParam)
        }
      })
    }
  }
  private async copyToNewVersion(param) {
    let res = await creatVersion({ ...param })
    if (res) {
      let processList = this.editingRoute.processList
      this.editingRoute = res.data
      this.$set(this.editingRoute, 'processList', processList)
      this.save()
      Message.success('创建成功')
    }
  }

  /**
   * 编辑工艺路线 - 保存
   */
  save() {
    if (this.validateSubmitProcessList()) {
      this.updateProcessRoute()
    }
  }
  async updateProcessRoute() {
    let result = await this.updata_VERSION({
      versionId: this.editingRoute.versionId,
      processList: this.editingRoute.processList
    })
    if (result) {
      console.log('updateProcessRoute')
      this.$message.success('保存成功')
      this.editingRoute = {}
      this.isEditing = false
      this.copyRouteDialogClose()
      this.getProcessRouteList()
    }
  }

  /**
   * 编辑工艺路线 - 保存时对工艺路线数据进行参数校验
   */
  private validateSubmitProcessList() {
    // 工艺路线至少包括两条工序 且 最后两道工序是整备和完工
    // 调试工时和定额工时如果没填默认设置为0
    console.log('提交的工序列表：')
    console.log(this.editingRoute.processList)
    let length = this.editingRoute.processList.length
    if (length < 2) {
      this.$alert('工艺路线应该以【整备】和【完工】结束', '错误提示')
      return false
    } else {
      for (let i = 0; i < this.editingRoute.processList.length; i++) {
        let currentProcess = this.editingRoute.processList[i]
        if (currentProcess.processName.length == 0) {
          this.$alert('工序' + (i + 1) + '不能为空', '错误提示')
          return false
        }
        if (currentProcess.department == '加工') {
          if (!/^[0-9]+([.][0-9]{1,2})?$/.test(currentProcess.debugHour)) {
            if (currentProcess.debugHour == '') {
              currentProcess.debugHour = 0
              this.processList[i].debugHour = 0
            } else {
              this.$alert('工序' + (i + 1) + '调试工时请输入整数或1-2位小数', '错误提示')
              return false
            }
          }
          if (!/^[0-9]+([.][0-9]{1,2})?$/.test(currentProcess.quotaHour)) {
            if (currentProcess.quotaHour == '') {
              currentProcess.quotaHour = 0
              this.processList[i].quotaHour = 0
            } else {
              this.$alert('工序' + (i + 1) + '定额工时请输入整数或1-2位小数', '错误提示')
              return false
            }
          }
        }
      }
      let processFinish = this.editingRoute.processList[length - 1]
      let processAssemblng = this.editingRoute.processList[length - 2]
      console.log(processFinish)
      console.log(processAssemblng)
      if (processAssemblng.processName != '整备' || processFinish.processName != '完工') {
        this.$alert('工艺路线应该以【整备】和【完工】结束', '错误提示')
      } else {
        return true
      }
    }
  }

  /**
   * 新建工艺路线
   */
  createNewRoute() {
    this.createRoute()
  }
  async createRoute() {
    let res = await creatVersion({ ...this.createRouteParam })
    if (res) {
      Message.success('创建成功')
      this.isEditing = true
      this.dialogVisible = false
      this.editingRoute = res.data
      // 响应数据中没有工序列表字段
      this.$set(this.editingRoute, 'processList', [])
      this.ifRouteEmptyAddOneProcess()
      this.sequencingProcess()
    }
  }

  /**
   * 如果受编辑的工艺路线为空 则添加一条空工艺
   */
  private ifRouteEmptyAddOneProcess() {
    if (this.editingRoute.processList.length == 0) {
      let emptyProcess = {
        sequenceNumber: 0,
        processName: '',
        department: '',
        single: true,
        debugHour: 0.0,
        quotaHour: 0.0
      }
      this.editingRoute.processList.push(emptyProcess)
    }
  }

  /**
   * 修改工艺路线后重新绑定工序号
   */
  private sequencingProcess() {
    for (let i = 0; i < this.editingRoute.processList.length; i++) {
      this.editingRoute.processList[i].sequenceNumber = i + 1
    }
  }

  /**
   * 编辑工艺路线 - 点击修改按钮
   */
  modifyRoute(route) {
    // 不在审核状态
    if (route.versionState == '待审核') {
      Message.warning('不在修改状态')
      return
    }
    // TODO 先向后端发送请求 判断是否可以修改
    this.canModifyRoute(route)
  }
  async canModifyRoute(route) {
    let res = await canModifyProcessRoute({ versionId: route.versionId })
    if (res) {
      this.editingRoute = _.cloneDeep(route)
      this.isEditing = true
      this.ifRouteEmptyAddOneProcess()
      this.sequencingProcess()
      return true
    }
    return false
  }
  /**
   * 删除工艺路线
   */
  deleteRoute(route) {
    this.$confirm('您确定删除该工艺路线？', '操作提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      type: 'warning'
    }).then(() => {
      this.deleteRouteConfirm(route.versionId)
    })
  }
  @vuexProcess.Action DELETE_VERSION: any
  async deleteRouteConfirm(versionId) {
    let result = await this.DELETE_VERSION({ versionId: versionId })
    if (result) {
      this.getProcessRouteList()
    }
  }

  /**
   * 工序输入框输入提示
   * 注意返回建议列表的数据格式
   * 需要是：{ value:"value" }
   */
  querySearch(queryString, cb) {
    let tempObjArray: any = []
    for (const iterator of this.processNameList) {
      let tempObj = {
        value: iterator
      }
      tempObjArray.push(tempObj)
    }
    var processList = tempObjArray
    var results = queryString ? processList.filter(this.createFilter(queryString)) : processList
    // 调用 callback 返回建议列表的数据
    cb(results)
  }
  createFilter(queryString: string) {
    return restaurant => {
      return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    }
  }
  /**
   * 编辑工艺路线 - 插入工序
   * @param sequenceNumber 当前工序工序号
   * @param dir +上 / +下
   */
  insertProcess(sequenceNumber, dir) {
    let newProcessIndex = dir ? Number(sequenceNumber) - 1 : Number(sequenceNumber)
    let process = {
      sequenceNumber: newProcessIndex,
      processName: '',
      department: '',
      single: true,
      debugHour: 0.0,
      quotaHour: 0.0
    }
    this.editingRoute.processList.splice(newProcessIndex, 0, process)
    // 重新对工序列表进行sequenceNumber绑定
    this.sequencingProcess()
  }

  /**
   * 编辑工艺路线 - 取消编辑
   */
  cancel() {
    this.editingRoute = {}
    this.isEditing = false
  }

  /**
   * 编辑工艺路线 - 删除工序
   */
  removeProcess(sequenceNumber) {
    this.editingRoute.processList.splice(sequenceNumber - 1, 1)
    this.ifRouteEmptyAddOneProcess()
    this.sequencingProcess()
  }

  /**
   * 自动填充整备与完工工序
   */
  addFinishProcess() {
    // 判断当前工序是否是空工序（未填）
    let currentProcessNumber = this.editingRoute.processList.length
    let currentRow = this.editingRoute.processList[currentProcessNumber - 1]
    if (currentRow.processName == "") {
      currentProcessNumber--
      this.editingRoute.processList.pop()
    }

    let assembling = {
      sequenceNumber: 0,
      processName: '整备',
      department: '加工',
      single: true,
      debugHour: 0.0,
      quotaHour: 0.0
    }

    assembling.sequenceNumber = currentProcessNumber + 1
    this.editingRoute.processList.splice(currentProcessNumber, 0, assembling)

    let finish = {
      sequenceNumber: 0,
      processName: '完工',
      department: '',
      single: true
    }
    finish.sequenceNumber = currentProcessNumber + 2
    this.editingRoute.processList.splice(currentProcessNumber + 1, 0, finish)
  }

  /**
   * 自动填充外协成品工艺模板
   */
  addOutsourceProcess() {
    // 判断当前工序是否是空工序（未填）或者为完工 若是则清除
    let currentProcessNumber = this.editingRoute.processList.length
    while (true) {
      let currentRow = this.editingRoute.processList[currentProcessNumber - 1]
      if (currentRow.processName == "" || currentRow.processName == "完工") {
        currentProcessNumber--
        this.editingRoute.processList.pop()
      } else {
        break
      }
      if (currentProcessNumber == 0) {
        break
      }
    }


    let outsource = {
      sequenceNumber: 0,
      processName: '外协成品',
      department: '外协',
      single: true,
      debugHour: 0.0,
      quotaHour: 0.0
    }

    outsource.sequenceNumber = currentProcessNumber + 1
    this.editingRoute.processList.splice(currentProcessNumber, 0, outsource)

    this.addFinishProcess()
  }

  /**
   * 自动填充采购成品工艺模板
   */
  addPurchaseProcess() {
    // 判断当前工序是否是空工序（未填）或者为完工 若是则清除
    let currentProcessNumber = this.editingRoute.processList.length
    while (true) {
      let currentRow = this.editingRoute.processList[currentProcessNumber - 1]
      if (currentRow.processName == "" || currentRow.processName == "完工") {
        currentProcessNumber--
        this.editingRoute.processList.pop()
      } else {
        break
      }
      if (currentProcessNumber == 0) {
        break
      }
    }


    let purchase = {
      sequenceNumber: 0,
      processName: '采购成品',
      department: '采购',
      single: true,
      debugHour: 0.0,
      quotaHour: 0.0
    }

    purchase.sequenceNumber = currentProcessNumber + 1
    this.editingRoute.processList.splice(currentProcessNumber, 0, purchase)

    this.addFinishProcess()
  }
}
</script>

<style lang="scss">
.add-procee-pane {
  padding: 20px 50px 0 50px;
}

.addProcessDetail-dialog {
  .icon-xiugai1:before {
    font-size: 12px;
  }

  .icon-shanchu1:before {
    font-size: 12px;
  }

  .el-switch__label.is-active>span {
    font-weight: bold;
    font-size: 18px;
  }
}

.route-table {
  text-align: center;

  th {
    padding: 0 !important;
    height: 50px;
    line-height: 50px;
  }

  td {
    padding: 0 !important;
    height: 50px;
    line-height: 50px;
  }
}

// .el-table .row-outsource-process {
//   background-color: tan;
// }
// .el-table .row-finish-process {
//   background-color: turquoise;
// }
// .el-table .row-nohour-process {
//   background-color: violet;
// }
// .el-table .row-work-process {
//   background-color: yellow;
// }</style>
